import re
import time
import os
import requests
import pygame
import json
# 设置请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
}

# 定义基础 URL
#重定向域名--需要修改
iurl = 'https://dyllbk.xxtt.info'
iurl_base = iurl + '/search/'
#搜索参数-名字
iurl_name = '%E7%A8%9A%E4%B9%96'  # 搜索的关键词，调整为需要的内容
url_2 = '/content/'

url_base= iurl + url_2
print(url_base)
#搜索的页
ipage = '/page/2'
response = requests.get(iurl_base + iurl_name + ipage, headers=headers)
print(iurl_base + iurl_name +ipage)
ihtml = response.text

# 提取每个作品的 URL
idir_name = re.findall(r'href="(.*?)" target="_self"', ihtml)
print(idir_name)

# 使用 set 去重
unique_urls = set(idir_name)

# 提取 https://www.4khd.com/content/ 后面的部分
trimmed_urls = [url.replace('https://www.4khd.com/content/', '') for url in unique_urls]
filtered_urls = [url for url in trimmed_urls if url != 'https://www.4khd.com']
print('nm',filtered_urls)
with open(f"{iurl_name}.json", "w") as json_file:
    json.dump(filtered_urls, json_file, indent=4)
#rint(trimmed_urls)

# 下载照片的函数
def download_photos(url_name):
    # 定义基础 URL

    # # url_name = '24/crazy-cat-ss-girls-wardrobe-one-piece-maid.html'  # 调整为你的具体 URL
    # url_name = input("请输入要下载的 URL 名称（例如 '24/crazy-cat-ss-girls-wardrobe-one-piece-maid.html'）：")
    page = ''  # 初始页码设置为空

    # 发送请求获取 HTML 代码
    response = requests.get(url_base + url_name + page, headers=headers)
    html = response.text
    #print(response.text)

    # 提取文件夹名称
    dir_name = re.findall(r'<h3 style="font-style:normal;font-weight:400;" class="wp-block-post-title has-medium-font-size">(.*?)</h3>',html)[-1]
    print(f"Folder Name: {dir_name}")  # 文件夹名字

    # 提取照片数量
    photos_num = re.findall(r'MB-(\d+)photos', html)
    photos_num = int(photos_num[0]) if photos_num else 0
    print(f"Total Photos: {photos_num}")  # 照片数量

    # 创建文件夹
    if not os.path.exists(dir_name):
        os.makedirs(dir_name)

    # 下载每一页的照片
    for page_num in range(1, (photos_num - 1) // 20 + 2):  # 计算需要下载的页数
        # 定义当前页面的 URL
        page_suffix = f"/{page_num}" if page_num > 1 else ""
        response = requests.get(url_base + url_name + page_suffix, headers=headers)
        html = response.text

        # 提取照片 URL
        urls = re.findall(r'src="(.*?)" width="1300" height="1500"', html)
        print(f"Downloading URLs from page {page_num}, found {len(urls)} URLs.")

        # 保存每一张照片
        for url in urls:
            time.sleep(0.5)  # 延迟以防被限制
            file_name = url.split('.')[-2] + '.png'
            print('正在下载', file_name)
            response = requests.get(url)
            with open(dir_name + '/' + file_name, 'wb') as file:
                file.write(response.content)
    print("所有照片下载完成！")
    pygame.mixer.init()

    # 加载音频文件
    pygame.mixer.music.load('x.wav')

    # 播放音频
    pygame.mixer.music.play()

    # 等待音乐播放结束
    while pygame.mixer.music.get_busy():
        pygame.time.wait(100)

# 遍历每个 URL 名称并下载照片
for url_name in filtered_urls:
    print(f"开始下载 {url_name} 的照片...")
    download_photos(url_name)